//Shamelessly copied(and modified) from the http://jqueryui.com/autocomplete/#combobox example

/**
 * Turns an inputbox into a combobox.
 */
$.widget('ilender.combobox',{
		_create:function(args){
			var input=$(this.element);
			var wasOpen=false;
			var wrapper=this.wrapper=$('<span></span>');
			var hiddenField=null;
			var allowFreeText=this.options.freetext;
			var lastSearch=[];
			if(input.is('[name]')){
				hiddenField=$('<input type="hidden"/>');
				hiddenField.attr('name',input.attr('name')+'_id');
				hiddenField.appendTo(wrapper);
				if(input.is('[hidden_field_initial_value]')){
					hiddenField.val(input.attr('hidden_field_initial_value'));
				}
			}
			wrapper.addClass('ui-combobox');
			wrapper.css('white-space','nowrap');
			wrapper.insertAfter(input);
			input.appendTo(wrapper);
			input.addClass("ui-combobox-input");
			input.autocomplete({
					delay:0,
					minLength:0,
					source:this.options.source,
					select:function(event,ui){
						$(this).val(ui.item.label);
						if(hiddenField){
							hiddenField.val(ui.item.value);
							hiddenField.data('keep_if_text_is',ui.item.label);
						}
						return false;
					},
					focus:function(event,ui){
						$(this).val(ui.item.label);
						if(hiddenField){
							hiddenField.val(ui.item.value);
							hiddenField.data('keep_if_text_is',ui.item.label);
						}
						return false;
					},
					response:function(event,ui){
						lastSearch=ui.content;
					},
					change:function(event,ui){
						var newText=$(this).val().trim();
						if(hiddenField&&hiddenField.data('keep_if_text_is')!=newText){
							var matches=$.grep(lastSearch,function(e){return newText==e.label;});
							if(0<matches.length){
								hiddenField.val(matches[0].value);
								hiddenField.data('keep_if_text_is',matches[0].label);
							}else if(allowFreeText){
								hiddenField.val('');
								hiddenField.removeData('keep_if_text_is');
							}else if(''!=newText){
								$(this).val(hiddenField.data('keep_if_text_is'));
							}else{
								hiddenField.val('');
								hiddenField.removeData('keep_if_text_is');
							}
						}
					}
			});
			var showAllButton=$('<a></a>');
			showAllButton.attr('tabIndex',-1);
			showAllButton.appendTo(wrapper);
			showAllButton.removeClass("ui-corner-all");
			showAllButton.addClass("ui-corner-right ui-combobox-toggle");
			showAllButton.button({
					icons:{
						primary:"ui-icon-triangle-1-s"
					},
					text:false
			});
			showAllButton.mousedown(function(){
					wasOpen=input.autocomplete("widget").is(":visible");
			});
			showAllButton.click(function(){
					input.focus();
					if(wasOpen){
						return;
					}else{
						input.autocomplete('search','');
					}
			});
		}
});
